<template>
  <div class="view-cropper">
    <el-upload
      ref="uploadRef"
      class="upload-demo"
      action=""
      :auto-upload="false"
      :on-change="handleChange"
      :show-file-list="false"
    >
      <template #trigger>
        <el-button v-if="!state.imgUrl" type="primary">选择上传</el-button>
        <img v-else :src="state.imgUrl" />
      </template>
    </el-upload>
    <el-dialog v-model="dialogVisible" title="图片裁剪" width="400px">
      <div class="cropper-div">
        <VueCropper
          ref="cropper"
          :img="option.img"
          :outputSize="option.outputSize"
          :outputType="option.outputType"
          :canScale="option.canScale"
          :autoCrop="option.autoCrop"
          :autoCropWidth="option.autoCropWidth"
          :autoCropHeight="option.autoCropHeight"
          :canMoveBox="option.canMoveBox"
          :canMove="option.canMove"
          :centerBox="option.centerBox"
          :info="option.info"
          :fixedBox="option.fixedBox"
          :fixed="option.fixed"
          :fixedNumber="option.fixedNumber"
          @realTime="realTime"
        ></VueCropper>
      </div>
      <!-- <div :style="previews.div" style="overflow:hidden; margin: 10px auto"> -->
      <div :style="previews.div" style="overflow: hidden; margin: 10px auto; width: 300px; height: 200px">
        <!-- <img :src="previews.url" :style="previews.img" class="imgsPerview"> -->
        <!-- <img :src="previews.url" :style="previews.img"> -->
        <img :src="cutData" style="width: 300px; height: 200px" />
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">Cancel</el-button>
          <el-button type="primary" @click="onOK">Confirm</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, defineEmits } from 'vue'
import { VueCropper } from 'vue-cropper'
import request from 'Common/request/index.js'
import axios from 'axios'
import { ElMessage } from 'element-plus'

const emits = defineEmits(['getbase'])
const uploadRef = ref()
const cropper = ref(null)
const fileData = ref()
const cutData = ref()
const dialogVisible = ref(false)
const previews = ref({
  url: '',
  width: '100px',
  height: '100px',
  img: ''
})
const state = reactive({
  ossData: {},
  imgUrl: ''
})

let option = reactive({
  img: fileData,
  outputSize: 1, // 裁剪生成图片质量
  outputType: 'jepg', // 裁剪生成图片格式
  canScale: true, // 图片是否允许滚轮播放
  autoCrop: true, // 是否默认生成截图框
  info: false, // 是否展示截图框信息
  // autoCropWidth: 150, // 生成截图框的宽度
  // autoCropHeight: 100, // 生成截图框的高度
  canMoveBox: true, // 截图框是否可以拖动
  fixedBox: false, // 固定截图框的大小
  canMove: false, // 上传图片是否可拖动
  centerBox: true, // 截图框限制在图片里面
  fixed: true,
  fixedNumber: [3, 2]
})

onMounted(() => {
  let url = 'https://test-fulanedu-mg.fairyclass.cn/aliyun/upload/policy'
  let param = {
    method: 'get',
    data: {
      date: Date.now()
    }
  }
  request(url, param).then((res) => {
    if (res.code == 1000) {
      state.ossData = res.data
    }
  })
})

const getPictureBase64 = (file) => {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.readAsDataURL(file)
    reader.onload = () => resolve(reader.result)
    reader.onerror = (error) => reject(error)
  })
}

const handleChange = async (file, files) => {
  // debugger
  if (file.raw) {
    if (file.raw.type?.includes('image')) {
      let imgFrontFileUrl = await getPictureBase64(file.raw)
      fileData.value = imgFrontFileUrl
      dialogVisible.value = true
    } else {
      ElMessage.error('请上传图片格式文件')
    }
  }
}

const realTime = (data) => {
  // previews.value = data;
  cropper.value.getCropData((datas) => {
    cutData.value = datas
  })
}

const dataURLtoFile = (dataurl, filename = 'file') => {
  let arr = dataurl.split(',')
  let mime = arr[0].match(/:(.*?);/)[1]
  let suffix = mime.split('/')[1]
  let bstr = atob(arr[1])
  let n = bstr.length
  let u8arr = new Uint8Array(n)
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n)
  }
  return new File([u8arr], `${filename}.${suffix}`, {
    type: mime
  })
}

const onOK = () => {
  cropper.value.getCropData((data) => {
    const suffix = '.png'
    const filename = Date.now() + suffix
    const fileData = dataURLtoFile(data)
    let formData = new FormData()
    formData.append('key', state.ossData.dir + '/' + filename)
    formData.append('OSSAccessKeyId', state.ossData.accessid)
    formData.append('policy', state.ossData.policy)
    formData.append('Signature', state.ossData.signature)
    formData.append('success_action_status', '200')
    formData.append('file', fileData)
    let param = {
      method: 'post',
      data: formData
    }
    axios(state.ossData.host, param).then((res) => {
      //https://fulan-edu.oss-cn-shanghai.aliyuncs.com/exerciseBook/1650852954042.png
      if (res.status == 200 && res.statusText?.toUpperCase() == 'OK') {
        let imgurl = `${state.ossData.host}/${state.ossData.dir}/${filename}`
        console.log('edu.oss.url==', imgurl)
        state.imgUrl = imgurl
        dialogVisible.value = false
        emits('getbase', imgurl)
      } else {
        ElMessage.error('上传失败')
        console.log('edu.oss.error', res)
      }
    })
  })
}
</script>

<style lang="less" scoped>
.view-cropper {
  .cropper-div {
    width: 300px;
    height: 300px;
    margin: 6px auto;
  }
  // .imgsPerview{
  // width: 300px !important;
  // }
}
</style>
